package calvin.controller.console;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.datanucleus.util.StringUtils;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;

public class RateGenController extends Controller {

    @Override
    public Navigation run() throws Exception {
        Date day = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        
        if(StringUtils.isEmpty(asString("day"))) {
            Date c = new Date(System.currentTimeMillis());
            String s = sdf.format(c);
            day = sdf.parse(s);
        } else {
            day = sdf.parse(asString("day"));
        }
        
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHH");
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyyMMddHHmm");
        for(int i = 0; i <= 24; i++) {
            Date h = new Date(day.getTime() + i * 60 * 60 * 1000);
            for(int j = 0; j <= 12; j++) {
                Date h5m = new Date(h.getTime() + 5 * 60 * 1000);
                Queue queue = QueueFactory.getQueue("rate-gen-queue");
                queue.add(TaskOptions.Builder.withUrl("/cron/generate5mTick").param("minute", sdf3.format(h5m)));   
            }
            Queue queue = QueueFactory.getQueue("rate-gen-queue");
            queue.add(TaskOptions.Builder.withUrl("/cron/generate1hTick").param("hour", sdf2.format(h)));
        }
        return forward("RateGen.jsp");
    }
}
